package com.xzz.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: hhz
 * @create: 2021-12-17 13:24
 * 144 给你二叉树的根节点 root ，返回它节点值的 前序 遍历。
 **/
public class Traversal {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(4);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(7);
        TreeNode node4 = new TreeNode(1);
        TreeNode node5 = new TreeNode(3);
        TreeNode node6 = new TreeNode(6);
        TreeNode node7 = new TreeNode(9);
        node2.left = node4;
        node2.right = node5;
        node3.left = node6;
        node3.right = node7;
        node1.left = node2;
        node1.right = node3;
        System.out.println(preorderTraversal(node1));


        TreeNode n1 = new TreeNode(3);
        TreeNode n2 = new TreeNode(1);
        TreeNode n3 = new TreeNode(2);
        n1.left = n2;
        n1.right = n3;
        System.out.println(postorderTraversal(n1));
    }
    public static List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        preTraversal(list,root);
        return list;
    }
    //前序
    public static void preTraversal(List<Integer> list,TreeNode root) {
        if (root != null) {
            list.add(root.val);
            preTraversal(list,root.left);
            preTraversal(list,root.right);
        }
    }
    public static List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        postTraversal(list,root);
        return list;
    }
    //后序
    public static void postTraversal(List<Integer> list,TreeNode root) {
        if (root != null) {
            postTraversal(list,root.left);
            postTraversal(list,root.right);
            list.add(root.val);
        }
    }

}
